package cn.tedu.test.rpc.demo04;

import cn.tedu.test.rpc.common.IUserService;
import cn.tedu.test.rpc.common.User;
import cn.tedu.test.rpc.demo03.UserServiceImpl;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

public class Demo04Server {
    private static boolean isRunning=true;
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket=new ServerSocket(8000);
        while(isRunning){
            Socket socket=serverSocket.accept();
            process(socket);
            socket.close();
        }
        serverSocket.close();
    }
    private static void process(Socket socket) throws Exception{
        InputStream inputStream=socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        ObjectInputStream oos=new ObjectInputStream(inputStream);
        DataOutputStream dos=new DataOutputStream(outputStream);

        String methodName=oos.readUTF();
        Class[] parameterTypes=(Class[])oos.readObject();
        Object[] args=(Object[])oos.readObject();

        IUserService service=new UserServiceImpl();
        Method method=service.getClass().getMethod(methodName,parameterTypes);
        Object all=method.invoke(service,args);

        //将方法返回数据，处理到输出流输出
        ObjectOutputStream oos1=new ObjectOutputStream(outputStream);
        oos1.writeObject(all);
        oos1.flush();
    }
}
